package Controller
{
	import Objects.ActionObject;
	
	import flash.events.KeyboardEvent;
	

	/**
	 * 键盘控制器
	 * @author Jian 2011.03.08
	 */
	public class KeyController extends BasicController
	{
		public function KeyController():void
		{
			super();
		}
		
		/**
		 * 安装侦听器
		 */
		public function setupListener():void
		{
			Global.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			Global.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		}
		
		/**
		 * 消亡
		 */
		override public function die():void
		{
			Global.stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			Global.stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		}
		
		/**
		 * 当按键按下时触发
		 * @param p_evt
		 */
		protected function onKeyDown(p_evt:KeyboardEvent):void
		{
			var me:ActionObject = _target as ActionObject;
			switch(p_evt.keyCode){
				case 38:
					me.direction = ActionObject.UP;
					break;
				case 40:
					me.direction = ActionObject.DOWN;
					break;
				case 37:
					me.direction = ActionObject.LEFT;
					break;
				case 39:
					me.direction = ActionObject.RIGHT;
					break;
				default:
					break;
			}
		}
		
		/**
		 * 当按键弹起时触发
		 * @param p_evt
		 */
		protected function onKeyUp(p_evt:KeyboardEvent):void
		{
			var me:ActionObject = _target as ActionObject;
			var active:Array = [37,38,39,40];
			//是预定义的按键弹起的话，方向置零
			if ( active.indexOf(p_evt.keyCode) != -1 ){
				me.direction = 0;
			}
		}
	}
}